"""
环境变量： 名称：RAINYUN_USER   如：用户名##密码##X-Api-Key
多账号新建变量或者用 & 分开
注册链接： https://www.rainyun.com/MTA4Nzc2_

定时：一天1-2次

更新日志：
2024-03-06

cron: 20 8 * * *
const $ = new Env("雨云");
"""
import json
import os

import requests

client = requests.session()


def get_token(username, password, api_key):
    res = client.post('https://api.v2.rainyun.com/user/login',
                      headers={"Content-Type": "application/json", 'x-api-key': api_key},
                      data=json.dumps({"field": f"{username}", "password": f"{password}"}))
    print(res.json())
    return res.cookies.get_dict()['X-CSRF-Token']


def sign_in(token, x_api_key):
    res = client.post('https://api.v2.rainyun.com/user/reward/tasks',
                      headers={
                          "Content-Type": "application/json",
                          'x-csrf-token': token,
                          'x-api-key': x_api_key,
                      },
                      data=json.dumps({"task_name": "每日签到", "verifyCode": ""})
                      )
    print(res.json())


if __name__ == '__main__':
    users = os.getenv('RAINYUN_USER')
    if users is None:
        print('请先设置 RAINYUN_USER 变量 格式：用户名##密码##X-Api-Key')
        exit()

    users = users.split('&')

    for user in users:
        userArr = user.split('##')
        if len(userArr) != 3:
            continue

        auth_token = get_token(userArr[0], userArr[1], userArr[2])
        sign_in(auth_token, userArr[2])
